package com.example.zhuma;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.Settings;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.example.zhuma.Manager.MediaManager;
import com.example.zhuma.adapter.RecorderAdapter;
import com.google.gson.Gson;
import com.example.zhuma.entity.Recorder;
import com.example.zhuma.tools.AudioRecorderButton;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VoiceActivity extends AppCompatActivity {
    //定义ListView要显示的时长列表
    private static final String[] timeLengthArray={"10'","10'","10'"};

    private ListView chatList;
    Gson gson=new Gson();
    //申请录音权限
    private static final int GET_RECODE_AUDIO = 1;
    private static String[] PERMISSION_AUDIO = {
            Manifest.permission.RECORD_AUDIO
    };
    //自定义按钮
    private AudioRecorderButton mAudioRecorderButton;
    private ArrayAdapter<Recorder> mAdapter;
    private List<Recorder> mDatas = new ArrayList<Recorder>();
    private View mAnimView=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_voice);
        //去除上方导航框
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        //设置显示聊天记录信息的文本内容ListView
        ListView chatList = findViewById(R.id.chatList);
        //声明一个映射对象的列表，用于表示心理知识的icon、title和content
        List<Map<String,Object>> list = new ArrayList<>();
        for (int i = 0; i < timeLengthArray.length; i++) {
            Map<String,Object> item = new HashMap<>();
            item.put("timeLength",timeLengthArray[i]);

            list.add(item);
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(this,list,R.layout.activity_msg_left
                ,new String[]{"timeLength"}
                ,new int[]{R.id.id_recorder_time});
        chatList.setAdapter(simpleAdapter);

        //Android动态获取权限许可简易模板
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (VoiceActivity.this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    VoiceActivity.this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                } else {
                    //这里就是权限打开之后自己要操作的逻辑
                }
            }
        }
        checkPermission();
        System.out.println(444);
        //允许在主线程进行网络请求
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        initView();
//        setListViewAdapter();
    }

    /**
     * 权限申请
     */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE};
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, permissions, 200);
                    return;
                }
            }
        }
    }

    private void initView() {
        chatList = findViewById(R.id.chatList);
        mAudioRecorderButton =findViewById(R.id.id_recorder_button);
        //实现录音准备完毕的接口回调方法
        mAudioRecorderButton.setAudioFinishRecorderListener(new AudioRecorderButton.AudioFinishRecorderListener() {
            @Override
            public void onFinish(float seconds, String filePath) throws IOException, SQLException {
                System.out.println(seconds);
                //每完成一次录音
                System.out.println(filePath);
                Recorder recorder = new Recorder(seconds, filePath,1);
                mDatas.add(recorder);
                mAdapter.notifyDataSetChanged();
                chatList.setSelection(mDatas.size() - 1);
            }
        });
    }

    private void setListViewAdapter() {
        mAdapter = new RecorderAdapter(this, mDatas);
        chatList.setAdapter(mAdapter);
        chatList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //如果第一个动画正在运行， 停止第一个播放其他的
                System.out.println(mAnimView!=null);
                if (mAnimView != null) {
                    mAnimView.setBackgroundResource(R.drawable.ic_launcher_background);
                    mAnimView = null;
                }
                //播放动画
//                mAnimView = view.findViewById(R.id.id_recorder_anim);
//                mAnimView.setBackgroundResource(R.drawable.ic_launcher_background);
//                AnimationDrawable animation = (AnimationDrawable) mAnimView.getBackground();
//                animation.start();

                //播放音频  完成后改回原来的background
                MediaManager.playSound(mDatas.get(position).getFilePath(), new MediaPlayer.OnCompletionListener() {

                    @Override
                    public void onCompletion(MediaPlayer mp) {
//                        mAnimView.setBackgroundResource(R.drawable.ic_launcher_background);
                    }
                });
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        MediaManager.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MediaManager.resume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MediaManager.release();
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestCode == 200) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivityForResult(intent, 200);
                    return;
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 200) {
            checkPermission();
        }
    }





}
